package com.sgb.kjwl.viewmodel.self.publish;

import android.annotation.SuppressLint;
import android.text.TextUtils;
import androidx.databinding.ObservableField;
import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.api.APIManager;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.lease.AskLeaseItemEntity;
import com.sgb.kjwl.model.entity.self.LeaseFarmEntity;
import com.sgb.kjwl.model.entity.transport.MapLongAndLatEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.model.entity.user.ServiceEntity;
import com.sgb.kjwl.model.entity.user.UnitEntity;
import com.sgb.kjwl.repository.SelfRepertory;
import com.swgk.core.event.EventConstant;
import com.sgb.link.event.LeaseEvent;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.kjwl.view.ui.activity.self.publish.LeaseFarmActivity;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LeaseFarmModel extends BaseViewModel {
    public ObservableField<LeaseFarmEntity> addLeaseEntity = new ObservableField<>(new LeaseFarmEntity());
    private LeaseFarmActivity activity;
    private SelfRepertory repertory;

    public LeaseFarmModel(LeaseFarmActivity activity, SelfRepertory repertory) {
        this.activity = activity;
        this.repertory = repertory;
    }

    //农机发布/编辑
    public void addOrUpdateEstate() {
        DialogHelper.showProgressDialog(activity, null, "发布中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getLeaseAPI().publishFarm(addLeaseEntity.get()).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() != null && response.body().getState().equals(AppConstant.REQEUST_SECCUESS)) {
                    if (addLeaseEntity.get().getId() != null) {
//                        MToast.showToast(activity, "编辑成功");
                        EventBus.getDefault().post(LoginEvent.make().setMessageTag(EventConstant.EVENT_FINISH_H5));//如果是从h5编辑跳转到app的,在编辑完成后关闭h5
//                    } else {
//                        MToast.showToast(activity, "发布成功");
                    }
                    EventBus.getDefault().post(LeaseEvent.make().setMessageTag(EventConstant.EVENT_LEASE_PUBLISH_FILTER));
                    activity.showSuccess();
                    activity.finish();
                } else {
                    if (response.body() != null && !TextUtils.isEmpty(response.body().getMsg())) {
                        MToast.showToast(activity, response.body().getMsg());
                    } else {
                        MToast.showToast(activity, "发布失败");
                    }
                    activity.showReNext(true);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                MToast.showToast(activity, "发送服务器失败");
                DialogHelper.dismissProgressDialog();
                activity.showReNext(true);
            }
        });
    }

    //农机出租编辑详情
    public void getEditDetail(String no) {
        DialogHelper.showProgressDialog(activity, null, "加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getLeaseAPI().detailFarm(no).enqueue(new Callback<BaseEntity<LeaseFarmEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<LeaseFarmEntity>> call, Response<BaseEntity<LeaseFarmEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if (null != response.body().getData() && null != response.body().getData()) {
                        activity.showEdit(response.body().getData());
                    } else {
                        MToast.showToast(activity, "暂无数据");
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<LeaseFarmEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity, "请求服务器失败");
            }
        });
    }


    //获取类型分类数据
    public void getTypeModel() {
        DialogHelper.showProgressDialog(activity, null, "加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getLeaseAPI().getCategorySelectFarm().enqueue(new Callback<BaseEntity<List<AskLeaseItemEntity<List<AskLeaseItemEntity>>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<AskLeaseItemEntity<List<AskLeaseItemEntity>>>>> call, Response<BaseEntity<List<AskLeaseItemEntity<List<AskLeaseItemEntity>>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if (null != response.body().getData() && null != response.body().getData()) {
                        activity.showTypeView(response.body().getData());
                    } else {
                        MToast.showToast(activity, "暂无数据");
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<AskLeaseItemEntity<List<AskLeaseItemEntity>>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity, "请求服务器失败");
            }
        });
    }


    //获取省市区
    public void getAddressModel() {
        APIManager.getInstance().getGoodsAPI().getCityList().enqueue(new Callback<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> call, Response<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> response) {
                if (response.body().getState().equals(APIManager.RESPONSE_OK))
                    activity.initAddressData(response.body().getData());
            }

            @Override
            public void onFailure(Call<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> call, Throwable t) {
                MLog.d(AppConstant.API_LOG, "error " + t.getMessage());
            }
        });
    }


    //获取经纬度信息
    public void getLocationLL(String provinceNo, String cityNo, String districtNo) {
        DialogHelper.showProgressDialog(activity, null, "加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getDriverAPI().getLocationLL(repertory.getAreaCode(), provinceNo, cityNo, districtNo).enqueue(new Callback<BaseEntity<MapLongAndLatEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<MapLongAndLatEntity>> call, Response<BaseEntity<MapLongAndLatEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.getLocationLL(response.body().getData());
                } else {
                    MToast.showToast(activity.getActivity(), response.message());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<MapLongAndLatEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity.getActivity(), t.getMessage());
            }
        });

    }

    //上传多图片
    public void uploadMutiFileModel(File file, int type, int completeNum) {
        Map<String, RequestBody> photos = new HashMap<>();
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        photos.put("file" + "\"; filename=\"" + completeNum + "image.jpg\"", requestBody);
        DialogHelper.showProgressDialog(activity, null, "图片上传中" + completeNum + "/" + activity.imgTotal + "...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUploadAPI().uploadFile(photos).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.uploadRefresh(response.body().getData().toString(), type);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity, t.getMessage());
            }
        });
    }

    //获取客服列表
    public void getCustomerOrgDataS() {
        APIManager.getInstance().getMachineAPI().getCustomerOrg().enqueue(
                new Callback<BaseEntity<List<ServiceEntity>>>() {
                    @Override
                    public void onResponse(Call<BaseEntity<List<ServiceEntity>>> call, Response<BaseEntity<List<ServiceEntity>>> response) {
                        if (response.body() == null) return;
                        activity.getCustomerOrgDataS(response.body().getData());
                    }

                    @Override
                    public void onFailure(Call<BaseEntity<List<ServiceEntity>>> call, Throwable t) {
                    }
                }
        );
    }

    /**
     * 获取价格单位
     */
    @SuppressLint("CheckResult")
    public void getPriceUnitModel(int type) {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getLeaseAPI().getPriceUnitSelectFarm().enqueue(new Callback<BaseEntity<List<UnitEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<UnitEntity>>> call, Response<BaseEntity<List<UnitEntity>>> response) {
                if (response.body() == null) return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.showUnitPop(response.body().getData(), type);
                    DialogHelper.dismissProgressDialog();
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<UnitEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //获取税率列表
    public void getLeaseRate() {
        APIManager.getInstance().getLeaseAPI().getLeaseRate().enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                if (response.body() == null) return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.showRate(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {
            }
        });
    }

    //获取申请部门
    public void getDepartment() {
        DialogHelper.showProgressDialog(activity, null, "数据获取中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getLeaseAPI().getUserDepartmentImg().enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.showDepartment(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //判断公司是否有审批
    public void haveApprovalOrNot(String companyNo,String type) {
        DialogHelper.showProgressDialog(activity, "加载中...").setCanceledOnTouchOutside(false);
        APIManager.getInstance().getLeaseAPI().haveApprovalOrNot(companyNo,type).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    try {//接口返回数据不标准,只能自行转换
                        JSONObject jsonObject = new JSONObject(response.body().getData().toString());
                        String str = jsonObject.getString("data");
                        //0无审批流 1 有审批流
                        activity.showPublishTip("1".equals(str));
                    } catch (JSONException e) {
                        e.printStackTrace();
                        MToast.showToast(activity, "服务异常");
                    }

                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

}
